package com.stlm2.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;

/**
 * Author：fuchunyu
 * Date：2017/8/3
 * Description：生成二维码
 */

public class QrcodeUtils {

	/**
	 * 生成二维码并输出
	 */
	public static void encode(String content, OutputStream outputStream){
		encode(content, 300, 300, outputStream);
	}

	/**
	 * 生成二维码并输出
	 */
	public static void encode(String content, int width, int height, OutputStream outputStream){
		try {
			Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
			// 指定纠错等级
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
			// 指定编码格式
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

			int[] rec = bitMatrix.getEnclosingRectangle();
			int resWidth = rec[2] + 1;
			int resHeight = rec[3] + 1;

			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
			resMatrix.clear();
			for (int i = 0; i < resWidth; i++) {
				for (int j = 0; j < resHeight; j++) {
					if (bitMatrix.get(i + rec[0], j + rec[1]))
						resMatrix.set(i, j);
				}
			}

			MatrixToImageWriter.writeToStream(resMatrix, "PNG", outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}